﻿#include <iostream>
#include <boost/asio.hpp>
#include <set>
using std::cout;
using std::endl;
using std::cerr;
const int MAX_SIZE = 1024;
std::shared_ptr<boost::asio::ip::tcp::socket>;
std::set<std::shared_ptr<std::thread>> set_thread;
void Session(std::shared_ptr<boost::asio::ip::tcp::socket> sock) {
    //cout << "shared_useCount: " << sock.use_count() << endl;
    while (1) {
        char buff[MAX_SIZE];
        memset(buff, 0, MAX_SIZE);
        boost::system::error_code ec;

        //sock.receive(boost::asio::buffer(buff, MAX_SIZE));
        sock->read_some(boost::asio::buffer(buff, MAX_SIZE), ec);
        if (ec) {
            cout << sock->remote_endpoint().address() << " peer exit" << endl;
            //cerr << "connection closed by peer" << endl;
            return;
        }
        cout << sock->remote_endpoint().address() << "ser receive message is: " << buff << endl;
        size_t length = strlen(buff);
        sock->send(boost::asio::buffer(buff, MAX_SIZE));
        memset(buff, 0, MAX_SIZE);
    }
}
int main()
{
    try {
        //创建服务
        boost::asio::io_context ioc;
        unsigned int port_num = 5555;
        //构造endpoint
        boost::asio::ip::tcp::endpoint ep(boost::asio::ip::tcp::v4(), port_num);
        //创建acceptor
        boost::asio::ip::tcp::acceptor acceptor(ioc, ep);
        cout << "server started" << endl;

        while (1) {
            //创建socket用于新接收的socket
            //boost::asio::ip::tcp::socket sock(ioc);
            std::shared_ptr<boost::asio::ip::tcp::socket> sock(new boost::asio::ip::tcp::socket(ioc));
            acceptor.accept(*sock);
            cout << "new cli is coming: " << sock->remote_endpoint().address() << endl;
            auto t = std::make_shared<std::thread>(Session, sock);
            
            //cout << "t.use_count()" << t.use_count() << endl;
            set_thread.insert(t);
        }
    }
    catch(boost::system::system_error& e){
        cout << "system_error: " << e.what() << endl;
    }
    return EXIT_SUCCESS;
}

